package com.jc.service.attribute;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ServiceException;
import com.jc.cds.model.CustomAttribute;
import com.jc.ds.base.service.BaseServiceImpl;
import com.jc.ds.mapper.BaseCustomMapper;
import com.jc.ds.model.Attribute;
import com.jc.ds.model.AttributeValue;
import com.jc.framework.enums.UsableStatus;
import com.jc.service.attributevalue.AttributeValueService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AttributeServiceImpl extends BaseServiceImpl<Attribute, CustomAttribute, Long> implements AttributeService {
	
	@Autowired
	AttributeValueService 	attributeValueService;

	@Override
	public BaseCustomMapper<CustomAttribute, Long> getCustomMapper() {
		return null;
	}
	@Transactional
	public void initAttribute(String attrDesc) throws Exception {
		JSONArray attrArray ;
		if(StringUtils.isBlank(attrDesc)) {
			throw new ServiceException("规格参数字符串为空");
		}
		try {
			attrArray = JSONArray.parseArray(attrDesc);
		} catch (Exception e) {
			getLOGGER().error("规格字符串转换错误,请检查是否为标准JSON格式！ , {}, {}" , e.getMessage(), e );
			throw new ServiceException("规格字符串转换错误,请检查是否为标准JSON格式！");
		}
		for(int i = 0 ; attrArray != null && i < attrArray.size() ; i++) {
			JSONObject att = attrArray.getJSONObject(i);
			if(att != null) {
				//处理属性名,如： 质量，尺码，尺寸，号码 ， 处理规则，有则跳过，无则添加
				String attName = att.getString("name");
				Attribute _attribute = new Attribute();
				_attribute.setProductAttributeName(attName);
				List<Attribute> queryAll = this.queryAll(_attribute);
				long attrId = 0l;
				if(CollectionUtils.isEmpty(queryAll)) {
					_attribute.setCreateTime(new Date());
					_attribute.setIsValid(UsableStatus.USABLE.getName());
					this.add(_attribute, false);
					attrId = _attribute.getId();
				}else {
					attrId = queryAll.get(0).getId();
				}
				if(att.getJSONObject("value") != null) {
					//同一规格名称下面，不能存在两个一样的属性值.
					String attValue = att.getJSONObject("value").getString("detailName");
					AttributeValue _attributeValue = new AttributeValue();
					_attributeValue.setAttributeNameId(attrId);
					_attributeValue.setAttributeValue(attValue);
					List<AttributeValue> queryAll2 = attributeValueService.queryAll(_attributeValue);
					if(CollectionUtils.isEmpty(queryAll2)) {
						_attributeValue.setAttributeName(attName);
						attributeValueService.add(_attributeValue, false);						
					}
				}
			}
		}
	}

	
}
